<?php

class Lib_Repair_Base_LT
{

    public static $messageCode = [

    ];
    private static function getConfig($key)
    {
        return Lib_Repair_Config::getConfig('LT')[$key];
    }
    private static function getTelXConf()
    {
        $env = getenv('RUNTIME_ENVIROMENT') ? getenv('RUNTIME_ENVIROMENT') : (defined('SHELL_VARIABLE') ? SHELL_VARIABLE : '');
        $env = empty($env)?'local':$env;
        $config = require(LIBRARY_DIR.'/Conf/'.$env.'/channel.php');
        return empty($config['TelX']) ? [] : $config['TelX'];
    }

    public function curlPost($url, $params)
    {
        //接口地址
        $api = self::getConfig('api');
        //请求token
        $token = self::getConfig('token');
        //header
        $headers[]  =  "Content-Type: application/json";
        $headers[]  =  "Authorization: Bearer ". $token;
        $logs = 'request_url : '.$api.$url;
        $logs .= ' token : '.$token;
        $logs .= ' request : '.json_encode($params);
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $api.$url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);

        $log = array();
        $res = curl_exec($ch);

        $log['errno'] = curl_errno($ch);
        $log['error'] = curl_error($ch);
        $log['httpcode'] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($log['errno'] !== 0) {
            curl_close($ch);
            $result['code'] = 401;
            $result['message'] = 'request fail errno'.$log['errno'];
            Func_Log::write('curl','curl_response401', $logs.'response : '.json_encode($log));
            return $result;
        }
        curl_close($ch);
        $logs .= "res = ".$res;
        $res = json_decode($res, true);
        if (!is_array($res) || count($res) <= 0) {
            //返回值错误日志
            $result['code'] = 401;
            $result['message'] = 'request fail errno'.$log['errno'];
            Func_Log::write('curl','curl_response401', $logs.'response : '.json_encode($log));
            return $result;
        }
        Func_Log::write('curl',   'curl_end', $logs.json_encode($log));
        return $res;
    }

    //建立请求数据
    public function buildData($data){
        $backtrace = debug_backtrace();
        array_shift($backtrace);
        $type = $backtrace[0]['function'];
        $post_data = [];
        if(empty($data)){
            return $post_data;
        }
        switch ($type)
        {
            case 'repair':
                foreach ($data as $k => $v){
                    if(Lib_Repair_Base_Tool::checkData($v,['repairName','sha256idCard'])){
                        $post_data[$k]['userName']  = $v['repairName'];
                        $post_data[$k]['idCard'] = $v['sha256idCard'];
                        $post_data[$k]['phone'] = empty($v['knownMobile']) ?  '' : $v['knownMobile'];
                    }
                }
                $post_data = ['data'=>$post_data];
                break;
            case 'getRepairResult':
                if(Lib_Repair_Base_Tool::checkData($data,['batchNo'])){
                    $post_data['batchId'] = $data['batchNo'];
                }
                break;
            case 'queryPhoneNum':
                if(Lib_Repair_Base_Tool::checkData($data,['batchNo','idCard'])){
                    $post_data['batchId']  = $data['batchNo'];
                    $post_data['idCard'] =  $data['idCard'];
                }
                break;
            case 'binding':
                if(Lib_Repair_Base_Tool::checkData($data,['batchNo','sha256idCard','repairmobile','telX','seatNumber','showNumber'])){
                    $post_data['batchId'] = $data['batchNo'];
                    $post_data['unicomCustomerId'] = $data['repairmobile'];
                    $post_data['idCard'] = $data['sha256idCard'];
                    $post_data['seatNumber'] = $data['seatNumber'];
                    $post_data['showNumber'] = empty($data['showNumber']) ? '' : $data['showNumber'];
                    $post_data['telX'] = $data['telX'];
                }
                break;
            case 'unbinding':
                if(Lib_Repair_Base_Tool::checkData($data,['bindId'])){
                    $post_data['bindId']  = $data['bindId'];
                }
                break;
            case 'sendMessageData':
                if(Lib_Repair_Base_Tool::checkData($data,['batchId','idCard','messageCode'])){
                    $post_data['batchId']  = $data['batchId'];
                    $post_data['idCard'] = hash("sha256", $data['idCard']);
                    $post_data['messageCode'] = $data['messageCode'];
                    $post_data['variableOne'] = empty($data['variableOne']) ? '' : $data['variableOne'];
                    $post_data['variableTwo'] = empty($data['variableTwo']) ? '' : $data['variableTwo'];
                    $post_data['variableThree'] = empty($data['variableThree']) ? '' : $data['variableThree'];
                    $post_data['variableFour'] = empty($data['variableFour']) ? '' : $data['variableFour'];
                    $post_data['variableFive'] = empty($data['variableFive']) ? '' : $data['variableFive'];
                }
                break;

        }
        return $post_data;
    }
    //获取可以绑定的小号
    public function getTelX(){
        $telX_set_key = Lib_Repair_Adapter_LianTong::$telX_set_key;
        $diffTel = [];
        //如果后台配置的鱼绑定的有差集，则随机返回一个
        if ($diffTel){
            $telX = $diffTel[array_rand($diffTel)];
            Func_Log::write('bindTel',   'success error', 'bindTel：'.$telX.' TelXConf: ' . json_encode($TelXConf)." bindindTel: ".json_encode(Lib_Redis_Set::sMembers($telX_set_key)));
            return $telX;
        }
        //如果都绑定了，可能异常可能不够用了，取配置里面的小号
        $confTel =  self::getTelXConf(); //联通配置中的小号
        //绑定中的和配置中的取差集，获取没有绑定的手机号
        $diffTel = array_diff($confTel,Lib_Redis_Set::sMembers($telX_set_key));
        if(empty($diffTel)){
            return false;
        }
        $telX = $diffTel[array_rand($diffTel)];
        Func_Log::write('bindTel',   'success error', 'bindTel：'.$telX.' TelXConf: ' . json_encode($TelXConf)." bindindTel: ".json_encode(Lib_Redis_Set::sMembers($telX_set_key)));
        return $telX;
    }
    //返回并记录日志
    public function returnData($code=200,$message='success',$data=[]){
        $backtrace = debug_backtrace();
        array_shift($backtrace);
        $type = $backtrace[0]['function'];
        $returnData = [
            'code' => $code,
            'message' => $message,
            'data' => $data,
        ];
        Func_Log::write('request','liantong'.'---'.$type.' --- '.$message, json_encode($returnData));
        return  $returnData;
    }

}